<template>
  <div class="role-management">
    <h1 style="color: #3998a9;">角色管理</h1>
    <el-button type="primary" @click="showDrawer('add')" class="add-btn">
      <el-icon>
        <plus />
      </el-icon>添加角色
    </el-button>
    <el-table :data="paginatedRoles" border style="width: 100% " class="role-table" :fit="true">
      <el-table-column prop="rolename" label="角色名称" min-width="120" align="center" header-align="center" />
      <el-table-column prop="description" label="说明" min-width="180" align="center" header-align="center" />
      <el-table-column prop="createdAt" label="创建时间" min-width="180" align="center" header-align="center" />
      <el-table-column prop="updatedAt" label="更新时间" min-width="180" align="center" header-align="center" />
      <el-table-column prop="isDefault" label="是否默认角色" align="center">
        <template #default="{ row }">
          <el-tag v-if="row.isDefault" type="success">是</el-tag>
          <el-tag v-else type="info">否</el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="isActive" label="状态" align="center">
        <template #default="{ row }">
          <div class="status-container">
            <el-tag v-if="row.isActive" type="success" @click="toggleRoleStatus(row)"
              style="cursor: pointer; padding: 6px 12px;">启用</el-tag>
            <el-tag v-else type="danger" @click="toggleRoleStatus(row)"
              style="cursor: pointer; padding: 6px 12px;">禁用</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280" align="center" header-align="center">
        <template #default="{ row }">
          <div class="operation-buttons">
            <el-button size="small" @click="openPermissionDialog(row)">权限管理</el-button>
            <el-button size="small" @click="openMenuDialog(row)">菜单管理</el-button>
            <el-button size="small" type="primary" @click="showDrawer('edit', row)">编辑</el-button>
            <el-button size="small" type="danger" @click="confirmDelete(row)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20]"
      layout="total, sizes, prev, pager, next, jumper" :total="totalRoles" class="pagination"
      @size-change="handleSizeChange" @current-change="handleCurrentChange" />

    <!-- 添加/编辑角色抽屉 -->
    <el-drawer v-model="drawerVisible" :title="drawerTitle" direction="rtl" size="60%">
      <el-form :model="currentRole" :rules="roleRules" ref="roleForm" label-width="100px" class="role-form">
        <el-form-item label="角色名称" prop="rolename">
          <el-input v-model="currentRole.rolename" placeholder="请输入角色名称，必填" :disabled="isEditing" />
        </el-form-item>
        <el-form-item label="说明" prop="description">
          <el-input v-model="currentRole.description" placeholder="请输入说明" />
        </el-form-item>
        <div class="form-row">
          <el-form-item label="是否默认角色">
            <el-switch v-model="currentRole.isDefault" />
          </el-form-item>
          <el-form-item label="角色状态">
            <el-switch v-model="currentRole.isActive" active-text="启用" inactive-text="禁用" />
          </el-form-item>
        </div>
        <el-form-item class="form-actions">
          <el-button type="primary" @click="saveRole">保存</el-button>
          <el-button @click="drawerVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>

    <!-- 删除确认对话框 -->
    <el-dialog v-model="deleteDialogVisible" title="确认删除" width="30%">
      <span>确定要删除角色 "{{ roleToDelete?.rolename }}" 吗？</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="handleDeleteRole">确认删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
  <!-- 权限管理弹窗 -->
  <el-dialog v-model="permissionDialogVisible" title="权限管理" width="40%">
    <div class="permission-management">
      <div class="permission-actions">
        <!-- <el-button size="small" @click="toggleAllPermissions">{{ permissionExpandText }}</el-button> -->
        <el-button size="small" @click="toggleSelectAllPermissions">{{ permissionSelectText }}</el-button>
        <el-button size="small" type="primary" @click="savePermissions">提交</el-button>
      </div>
      <el-scrollbar height="400px" class="permission-list">
        <el-checkbox-group v-model="checkedPermissionIds" class="permission-column">
          <el-checkbox v-for="item in permissionData" :key="item.id" :label="item.id" class="permission-item">
            {{ item.permissionname }}
          </el-checkbox>
        </el-checkbox-group>
      </el-scrollbar>
    </div>
  </el-dialog>

  <!-- 菜单管理弹窗 -->
  <el-dialog v-model="menuDialogVisible" title="菜单管理" width="40%">
    <div class="menu-management">
      <div class="menu-actions">
        <el-button size="small" @click="toggleAllMenus">{{ menuExpandText }}</el-button>
        <el-button size="small" @click="toggleSelectAllMenus">{{ menuSelectText }}</el-button>
        <el-button size="small" type="primary" @click="saveMenus">提交</el-button>
      </div>
      <el-tree ref="menuTree" :data="menuData" show-checkbox node-key="id" :props="menuProps" class="menu-tree" />
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getRoleList, getRoleMenuList, getRolePermissionList, addRole, editRole, deleteRole, assignPermissions, assignMenus, getRoleDetail, enableRole, disableRole, } from '@/api/role'
import { useMenuStore } from '@/stores/menuStore'
// 角色数据
const roles = ref([])
const totalRoles = ref(0)
// 菜单数据从store获取
const menuData = ref([])

// 权限数据
const permissionData = ref([])

// 权限管理相关
const checkedPermissionIds = ref([])   // 已选权限 id
const permissionSelectText = ref('全部选择')

// 菜单管理相关
const menuTree = ref(null)
const menuCheckedKeys = ref([])
const menuExpandText = ref('全部展开')
const menuSelectText = ref('全部选择')
const menuProps = {
  children: 'children',
  label: 'menuname'
}
// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const paginatedRoles = computed(() => {
  return roles.value
})

// 加载角色数据
const loadRoles = async () => {
  try {
    const response = await getRoleList({ pageIndex: currentPage.value, pageSize: pageSize.value })
    if (response.code === 200) {
      roles.value = [...(response.data.items || [])]
      totalRoles.value = response.data.totalCount || 0
      // console.log('角色数据', roles.value) // 打印角色数据
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    ElMessage.error(error.message || '网络错误')
  }
}

// 加载权限数据
const loadPermissions = async () => {
  try {
    const response = await getRolePermissionList() // 拉全部
    // console.log('权限接口返回', response)
    if (response.code === 200) {
      // 转换为 el-tree 需要的字段
      permissionData.value = response.data
        .filter(p => p.isActive !== false) // 后端字段假设为 isActive
        .map(p => ({
          id: p.permissionId,
          permissionname: p.permissionname
        }))
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    ElMessage.error(error.message || '网络错误')
  }
}
//加载菜单数据
const loadMenus = async () => {
  try {
    const response = await getRoleMenuList()
    if (response.code === 200) {
      menuData.value = response.data || []
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    ElMessage.error(error.message || '网络错误')
  }
}
// 组件挂载时加载数据
onMounted(async () => {
  await loadRoles()
  await loadMenus()
  await loadPermissions()
})
// 抽屉相关
const drawerVisible = ref(false)
const drawerTitle = ref('')
const isEditing = ref(false)
const roleForm = ref(null)
const currentRole = ref({
  id: '',
  rolename: '',
  description: '',
  isDefault: false,
  isActive: true,
})



// 表单验证规则
const roleRules = {
  rolename: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入角色说明', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ]
}

// 显示抽屉
const showDrawer = async (type, row) => {

  if (type === 'add') {
    drawerTitle.value = '添加角色'
    isEditing.value = false
    currentRole.value = {
      rolename: '',
      description: '',
      isDefault: false,
      isActive: true,
    }
  } else {
    drawerTitle.value = '编辑角色'
    isEditing.value = true
    const response = await getRoleDetail(row.id)
    if (response.code === 200) {
      console.log('角色详情接口返回', response.data);
      currentRole.value = { ...row }
    } else {
      ElMessage.error(response.message)
      return
    }
  }
  drawerVisible.value = true

}

// 保存角色
const saveRole = async () => {
  roleForm.value.validate(async (valid) => {
    if (!valid) return
    try {
      const payload = {
        rolename: currentRole.value.rolename,
        description: currentRole.value.description,
        isDefault: currentRole.value.isDefault,
        isActive: currentRole.value.isActive
      }
      const res = isEditing.value
        ? await editRole(currentRole.value.id, payload)
        : await addRole(payload)
      if (res.code === 200) {
        ElMessage.success(res.data)
        drawerVisible.value = false
        await loadRoles()

        // 角色创建/编辑后，刷新用户菜单数据
        const menuStore = useMenuStore()
        await menuStore.fetchUserMenuTree()
      } else {
        ElMessage.error(res.message)
      }
    } catch (e) {
      ElMessage.error(e.message || '网络错误')
    }
  })
}
// 删除相关
const deleteDialogVisible = ref(false)
const roleToDelete = ref(null)
// 确认删除
const confirmDelete = (role) => {
  roleToDelete.value = role
  deleteDialogVisible.value = true
}
// 执行删除
const handleDeleteRole = async () => {
  try {

    const response = await deleteRole(roleToDelete.value.id)
    if (response.code === 200) {
      ElMessage.success(response.data)
      // 如果当前页只剩1条且不是第一页，先减页码
      if (roles.value.length === 1 && currentPage.value > 1) {
        currentPage.value--
      }
      await loadRoles()

      // 角色删除后，刷新用户菜单数据
      const menuStore = useMenuStore()
      await menuStore.fetchUserMenuTree()
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    ElMessage.error(error.message || '网络错误')
  }
  deleteDialogVisible.value = false
}
// 打开权限管理弹窗
const permissionDialogVisible = ref(false)
// const openPermissionDialog = async (row) => {

//   // 获取最新角色详情
//   const response = await getRoleDetail(row.id)
//   if (response.code === 200) {
//     checkedPermissionIds.value = (response.data.permissions || []).map(p => p.permissionId)
//     currentRole.value.id = row.id
//     permissionDialogVisible.value = true
//     const all = permissionData.value.map(p => p.id)
//     const allSelected = all.length > 0 && all.every(id => checkedPermissionIds.value.includes(id))
//     permissionSelectText.value = allSelected ? '取消全选' : '全部选择'
//   } else {
//     ElMessage.error(response.message)
//   }
// }
const openPermissionDialog = async (row) => {
  //先把整表刷新，拿到最新数据
  await loadRoles()

  // 在最新的 roles 里找到当前这一行
  const freshRow = roles.value.find(r => r.id === row.id)
  if (!freshRow) return

  // 用 freshRow 里的权限来回显
  const response = await getRoleDetail(freshRow.id)
  console.log('getRoleDetail 返回', response.data.permissions)
  if (response.code === 200) {
    checkedPermissionIds.value = (response.data.permissions || []).map(p => p.permissionId)
    currentRole.value.id = freshRow.id
    permissionDialogVisible.value = true

    const all = permissionData.value.map(p => p.id)
    const allSelected = all.length > 0 && all.every(id => checkedPermissionIds.value.includes(id))
    permissionSelectText.value = allSelected ? '取消全选' : '全部选择'
  } else {
    ElMessage.error(response.message)
  }
}
// 提交权限设置
const savePermissions = async () => {
  if (!currentRole.value.id) return
  try {
    const res = await assignPermissions(currentRole.value.id, {
      PermissionIds: checkedPermissionIds.value
    })
    if (res.code === 200) {
      ElMessage.success(res.data)
      permissionDialogVisible.value = false
      await loadRoles()

      // 权限分配后，刷新用户菜单数据
      const menuStore = useMenuStore()
      await menuStore.fetchUserMenuTree()

      const detail = await getRoleDetail(currentRole.value.id)
      console.log('提交后角色详情', detail.data.permissions)
    } else {
      ElMessage.error(res.message)
    }
  } catch (e) {
    ElMessage.error(e.message || '网络错误')
  }
}

// 打开菜单管理弹窗
const menuDialogVisible = ref(false)
const openMenuDialog = async (row) => {
  menuCheckedKeys.value = []
  //拉取已绑定的菜单id列表
  const response = await getRoleDetail(row.id)

  if (response.code === 200) {
    //读取后端返回的数组
    // 假设 row.menus 是 [{menuId, menuname}]
    const ids = (response.data.menus || []).map(m => m.id)
    menuCheckedKeys.value = ids
    currentRole.value.id = row.id
    menuDialogVisible.value = true

    nextTick(() => {
      menuTree.value?.setCheckedKeys([]) //  先清空
      menuTree.value?.setCheckedKeys(ids, false) // 再设置当前角色的
      const allKeys = getAllKeys(menuData.value)
      const checked = menuTree.value.getCheckedKeys(false)
      const allSelected = allKeys.length && allKeys.every(k => checked.includes(k))
      menuSelectText.value = allSelected ? '取消全选' : '全部选择'
      menuExpandText.value = '全部展开'
    })
  } else {
    ElMessage.error(response.message)
  }
}

// 提交菜单设置
const saveMenus = async () => {
  if (!currentRole.value.id) return

  // 只保留叶子
  const leafOnly = menuTree.value.getCheckedKeys(true)
  try {
    const response = await assignMenus(currentRole.value.id, { MenuIds: leafOnly })// 后端只要求 MenuIds 数组
    if (response.code === 200) {
      ElMessage.success(response.data)
      menuDialogVisible.value = false
      await loadRoles()

      // 刷新用户菜单数据，确保布局组件菜单栏及时更新
      const menuStore = useMenuStore()
      await menuStore.fetchUserMenuTree()
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    ElMessage.error(error.message || '网络错误')
  }
}




// 切换角色状态
// 状态切换
const toggleRoleStatus = async row => {
  const old = row.isActive
  try {
    const res = old ? await disableRole(row.id) : await enableRole(row.id)
    if (res.code === 200) {
      ElMessage.success(res.data)
      row.isActive = !old

      // 角色状态变更后，刷新用户菜单数据
      const menuStore = useMenuStore()
      await menuStore.fetchUserMenuTree()
    } else {
      ElMessage.error(res.message)
    }
  } catch (e) {
    ElMessage.error(e.message || '网络错误')
  }
}
// 分页事件处理
const handleSizeChange = (size) => {
  pageSize.value = size
  loadRoles()
}

const handleCurrentChange = (current) => {
  currentPage.value = current
  loadRoles()
}




//实现全部收起展开/全部选择未选择功能
const toggleSelectAllPermissions = () => {
  const all = permissionData.value.map(p => p.id)
  // 判断是否“已经全部选中”
  const allSelected = all.length > 0 && all.every(id => checkedPermissionIds.value.includes(id))
  if (allSelected) {
    // 已全选 → 取消全选
    checkedPermissionIds.value = []
    permissionSelectText.value = '全部选择'
  } else {
    // 未全选 → 全选
    checkedPermissionIds.value = all
    permissionSelectText.value = '取消全选'
  }
}
// 菜单管理方法
const toggleAllMenus = () => {
  nextTick(() => {
    const tree = menuTree.value;
    if (!tree || !menuData.value.length) return;

    const allExpanded = tree.store._getAllNodes().some(n => n.expanded);
    const newState = !allExpanded;

    tree.store._getAllNodes().forEach(n => n[newState ? 'expand' : 'collapse']());
    menuExpandText.value = newState ? '全部收起' : '全部展开';
  });
};

const getAllKeys = (data) => {
  const keys = []
  const walk = (arr) => {
    arr.forEach(item => {
      keys.push(item.id)
      if (item.children?.length) walk(item.children);
    })
  }
  walk(data)
  return keys
}
// 全选 / 取消全选
const toggleSelectAllMenus = () => {
  nextTick(() => {
    if (!menuTree.value || !menuData.value.length) return;
    const allKeys = getAllKeys(menuData.value);
    const checked = menuTree.value.getCheckedKeys(false);
    const allSelected = allKeys.length && allKeys.every(k => checked.includes(k));
    // menuTree.value.setCheckedKeys(allSelected ? [] : allKeys);
    // menuSelectText.value = allSelected ? '全部选择' : '取消全选';

    if (allSelected) {
      menuTree.value.setCheckedKeys([])
      menuSelectText.value = '全部选择'
    } else {
      menuTree.value.setCheckedKeys(allKeys)
      menuSelectText.value = '取消全选'
    }
  });
};


</script>

<style scoped>
.role-management {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

h1 {
  margin-bottom: 20px;
  color: #333;
  font-weight: 600;
}

.add-btn {
  margin-bottom: 20px;
}

.role-table {
  margin-bottom: 60px;
}

.role-table :deep(.el-table__cell) {
  padding: 12px 0;
}

.role-table :deep(.el-table th.el-table__cell) {
  background-color: #f5f7fa;
  font-weight: 600;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}

.menu-permission-container {
  padding: 10px;
}

.menu-actions {
  margin-bottom: 15px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.menu-tree {
  max-height: 60vh;
  overflow-y: auto;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.menu-status {
  color: #67c23a;
  font-weight: bold;
  margin-left: 10px;
}

.el-drawer__header {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.el-form {
  padding: 20px;
}

:deep(.el-tree-node__content) {
  height: 36px;
  line-height: 36px;
}

:deep(.el-tree-node__label) {
  font-size: 14px;
}

:deep(.el-checkbox) {
  margin-right: 8px;
}

.role-tabs {
  margin-bottom: 20px;
}

.permission-management,
.menu-management {
  padding: 10px;
}

.permission-actions,
.menu-actions {
  margin-bottom: 15px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.permission-tree,
.menu-tree {
  max-height: 50vh;
  overflow-y: auto;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.role-management {
  padding: 20px;
}

.add-btn {
  margin-bottom: 20px;
}

.role-table {
  margin-bottom: 20px;
}

.pagination {
  text-align: right;
}

.status-container {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.status-tag {
  min-width: 60px;
}

.operation-buttons {
  display: flex;
  justify-content: center;
}

.role-form {
  padding: 20px 0;
}

.form-row {
  display: flex;
  gap: 40px;
  margin-bottom: 20px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 30px;
}

.permission-column {
  display: flex;
  flex-direction: column;
  gap: 8px;
  /* 可调整间距 */
}

.permission-item {
  font-size: 14px;
}

.permission-list {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 8px 12px;
}

.permission-item {
  display: block;
  margin: 8px 0;
  font-size: 14px;
}
</style>
